<template>
  <div class="edit-order">
    <h2>订单详情</h2>
    <div class="order-container">
      <!-- 左侧部分 -->
      <div class="left-section">
        <el-form :model="order" label-width="120px" class="order-form">
          <!-- 订单管理员 -->
          <el-form-item label="订单管理员">
            <el-input v-model="order.order_admin" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="订单ID">
            <el-input v-model="order.order_id" :disabled="true"></el-input>
          </el-form-item>
          <!-- 订单名称 -->
          <el-form-item label="订单名称">
            <el-input v-model="order.order_name" :disabled="true"></el-input>
          </el-form-item>
          <!-- 订单价格 -->
          <el-form-item label="订单价格">
            <el-input v-model="order.order_price" type="number" :disabled="true"></el-input>
          </el-form-item>
          <!-- 订单状态 -->
          <el-form-item label="订单状态">
            <el-select v-model="order.order_status" :disabled="true">
              <el-option label="未付款" :value="7"></el-option>
              <el-option label="支付待审核" :value="1"></el-option>
              <el-option label="待发货" :value="2"></el-option>
              <el-option label="已发货" :value="3"></el-option>
              <el-option label="已签收" :value="4"></el-option>
              <el-option label="审核未通过" :value="5"></el-option>
              <el-option label="已退货" :value="6"></el-option>
            </el-select>
          </el-form-item>
          <!-- 联系电话 -->
          <el-form-item label="联系电话">
            <el-input v-model="order.order_phone" :disabled="true"></el-input>
          </el-form-item>
          <!-- 收货地址 -->
          <el-form-item label="收货地址">
            <el-input v-model="order.order_address" :disabled="true"></el-input>
          </el-form-item>
          <!-- 省份 -->
          <el-form-item label="省份">
            <el-select v-model="order.order_province" placeholder="请选择省份" :disabled="true">
              <el-option v-for="province in provinces" :key="province" :label="province" :value="province"></el-option>
            </el-select>
          </el-form-item>
          <!-- 备注 -->
          <el-form-item label="备注">
            <el-input v-model="order.order_remark" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="物流信息" v-if="order.order_status === 3 || order.order_status === 4">
            <div v-if="logisticsInfo">
              <p>物流单号: {{ logisticsInfo.logistics_number }}</p>
              <p>物流公司: {{ logisticsInfo.logistics_name }}</p>
              <p>发货时间: {{ logisticsInfo.logistics_time }}</p>
            </div>
            <div v-else>
              <p>暂无物流信息</p>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 右侧部分 -->
      <div class="right-section">
        <el-form :model="order" label-width="120px" class="order-form">
          <!-- 商品列表 -->
          <el-form-item label="商品列表">
            <table class="goods-table">
              <thead>
                <tr>
                  <th>商品ID</th>
                  <th>商品名称</th>
                  <th>商品数量</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(goods, index) in order.bs_order_goods" :key="index">
                  <td>{{ goods.goods_id }}</td>
                  <td>{{ goods.goods_name }}</td>
                  <td>{{ goods.goods_num }}</td>
                </tr>
              </tbody>
            </table>
          </el-form-item>

          <!-- 支付凭证操作区域 -->
          <el-form-item label="支付凭证">
            <div v-if="order.order_status === 7 || order.order_status === 5">
              <div>
                <input type="file" @change="handleFileChange" />
                <el-button v-if="selectedFile" type="danger" @click="clearSelectedFile">删除选择的图片</el-button>
              </div>
              <el-form-item label="支付ID">
                <el-input v-model="payId"></el-input>
              </el-form-item>
              <el-form-item label="支付编号">
                <el-input v-model="payNumber"></el-input>
              </el-form-item>
              <el-button type="primary" @click="uploadImage" :disabled="!selectedFile">上传支付凭证</el-button>
            </div>
            <div v-else>
              <p>支付成功</p>
              <el-form-item label="支付ID">
                <el-input v-model="order.pay_id" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="支付编号">
                <el-input v-model="order.pay_number" :disabled="true"></el-input>
              </el-form-item>
              <img v-if="imageData" :src="`data:image/jpeg;base64,${imageData}`" alt="支付凭证" class="payment-image">
            </div>
          </el-form-item>

          <!-- 物流信息 -->
    

          <!-- 操作按钮 -->
          <el-form-item>
            <el-button type="primary" @click="updateOrder">更新</el-button>
            <el-button @click="goBack">返回订单列表</el-button>
            <div v-if="order.order_status === 3">
              <el-button type="primary" @click="sign">确认签收</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      order: {
        order_admin: '',
        order_name: '',
        order_price: 0,
        order_status: 1,
        order_phone: '',
        order_address: '',
        order_province: '',
        order_remark: '',
        bs_order_goods: [], // 商品列表
        pay_id: '', // 支付ID
        pay_number: '' // 支付编号 
      },
      provinces: ['北京', '上海', '广东', '广西', '江苏', '浙江', '四川', '湖北', '河北', '河南', '云南', '辽宁', '黑龙江', '湖南', '安徽', '山东', '新疆', '甘肃', '山西', '内蒙古', '陕西', '吉林', '江西', '贵州', '海南', '宁夏', '青海', '西藏', '重庆', '天津'],
      selectedFile: null,
      imageData: '',
      payId: '',
      payNumber: '',
      logisticsInfo: null // 物流信息
    };
  },
  created() {
    this.fetchOrder();
  },
  methods: {
    // 获取订单数据
    fetchOrder() {
      const orderId = this.$route.params.id; // 从路由参数中获取订单ID
      axios.get(`http://127.0.0.1:3005/order/getOrders`)
        .then(response => {
          if (response.data && response.data.res && response.data.res.result) {
            const orders = response.data.res.result;
            const targetOrder = orders.find(order => order.order_id === orderId);
            if (targetOrder) {
              this.order = targetOrder; // 填充表单数据
              if (targetOrder.order_status !== 7 && targetOrder.order_status !== 5) {
                this.showImage(); // 如果订单已支付且不是未付款和审核不通过，显示支付凭证
              }
              // 如果订单状态是已发货或已签收，获取物流信息
              if (targetOrder.order_status === 3 || targetOrder.order_status === 4) {
                this.fetchLogisticsInfo(orderId);
              }
            } else {
              this.$message.error('未找到该订单');
            }
          } else {
            this.$message.error('订单数据格式错误');
          }
        })
        .catch(error => {
          console.error(error);
          this.$message.error('订单查询失败');
        });
    },
    fetchLogisticsInfo(orderId) {
      axios.get(`http://127.0.0.1:3005/order/getlogistics/${orderId}`)
        .then(response => {
          if (response.data && response.data.res && response.data.res.result) {
            this.logisticsInfo = response.data.res.result;
          } else {
            this.$message.error('物流信息格式错误');
            this.logisticsInfo = null; // 清空物流信息
          }
        })
        .catch(error => {
          console.error(error);
          this.$message.error('获取物流信息失败');
          this.logisticsInfo = null; // 清空物流信息
        });
    },
    // 更新订单
    updateOrder() {
      const orderId = this.$route.params.id;
      axios.post(`http://127.0.0.1:3005/order/updateOrder/${orderId}`, this.order)
        .then(() => {
          this.$message.success('订单更新成功');
          this.$router.go(-1); // 跳转到订单列表页面
        })
        .catch(error => {
          console.error(error);
          this.$message.error('订单更新失败');
        });
    },
    // 返回订单列表
    goBack() {
      this.$router.go(-1);
    },
    handleFileChange(e) {
      const file = e.target.files[0];
      if (file) {
        const fileSize = file.size / 1024; // 将文件大小转换为 KB
        if (fileSize > 60) {
          this.$message.error('图片大小不能超过60KB，请重新选择');
          this.clearSelectedFile();
          return;
        }
        this.selectedFile = file;
      }
    },
    // 清除已选择的文件
    clearSelectedFile() {
      this.selectedFile = null;
      const input = document.querySelector('input[type="file"]');
      if (input) {
        input.value = ''; // 清空 input 的值
      }
    },
    // 压缩图片的函数
    compressImage(file, quality = 0.7) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);

        reader.onload = (e) => {
          const img = new Image();
          img.src = e.target.result;

          img.onload = () => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');

            // 设置 canvas 的宽度和高度
            canvas.width = img.width;
            canvas.height = img.height;

            // 将图片绘制到 canvas 上
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

            // 将 canvas 内容转换为 Blob 对象
            canvas.toBlob((blob) => {
              if (blob) {
                resolve(blob);
              } else {
                reject(new Error('图片压缩失败'));
              }
            }, file.type, quality);
          };

          img.onerror = () => {
            reject(new Error('图片加载失败'));
          };
        };

        reader.onerror = () => {
          reject(new Error('图片读取失败'));
        };
      });
    },
    // 上传图片的异步函数
    async sign() {
      this.order.order_status = 4; // 更新订单状态为已完成
      this.updateOrder(); // 更新订单 
    },
    async uploadImage() {
      if (!this.selectedFile) {
        alert('请选择一张图片');
        return;
      }
      if (!this.payId || !this.payNumber) {
        alert('请输入支付ID和支付编号');
        return;
      }

      try {
        const compressedBlob = await this.compressImage(this.selectedFile);

        const reader = new FileReader();
        reader.readAsDataURL(compressedBlob);

        reader.onload = async () => {
          const base64Data = reader.result.split(',')[1];

          const data = {
            order_id: this.order.order_id,
            pay_id: this.payId,
            pay_url: base64Data,
            pay_number: this.payNumber
          };

          const response = await axios.post('http://127.0.0.1:3005/order/createpay', data);
          console.log('图片上传成功:', response.data);
          alert('图片上传成功');
          this.order.order_status = 1; // 更新订单状态为已完成
          this.updateOrder(); // 更新订单
        };

        reader.onerror = () => {
          console.error('图片读取失败');
          alert('图片读取失败');
        };
      } catch (error) {
        console.error('图片上传失败:', error);
        alert('图片上传失败');
      }
    },
    async showImage() {
      try {
        const response = await axios.get(`http://127.0.0.1:3005/order/getpay/${this.order.order_id}`);
        this.imageData = response.data.res.result.pay_url;
        this.order.pay_id = response.data.res.result.pay_id; // 获取支付ID
        this.order.pay_number = response.data.res.result.pay_number; // 获取支付编号
      } catch (error) {
        console.error('获取图片失败:', error);
        alert('获取图片失败');
      }
    },
    // 提交物流信息
    submitLogistics() {
      if (!this.logisticsName || !this.logisticsNumber || !this.logisticsTime) {
        this.$message.error('请填写完整的物流信息');
        return;
      }
      const data = {
        order_id: this.order.order_id,
        logistics_name: this.logisticsName,
        logistics_number: this.logisticsNumber,
        logistics_time: this.logisticsTime
      };
      axios.post('http://127.0.0.1:3005/order/logistics', data)
        .then(() => {
          this.$message.success('物流信息提交成功');
          this.order.order_status = 3; // 更新订单状态为已发货
          this.updateOrderStatus();
        })
        .catch(error => {
          console.error(error);
          this.$message.error('物流信息提交失败');
        });
    }

  }
};
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css?family=Roboto:400,500,700&display=swap');

.edit-order {
  padding: 20px;
  max-width: 1400px; /* 增加最大宽度 */
  margin: 0 auto;
  font-family: 'Roboto', sans-serif;
  background-color: #e6f0ff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.title {
  color: #164f9a;
  font-size: 24px;
  margin-bottom: 20px;
  border-bottom: 2px solid #164c92;
  padding-bottom: 10px;
}

.order-container {
  display: flex; /* 使用 flexbox 布局 */
  gap: 5px; /* 左右部分之间的间距 */
}

.left-section,
.right-section {
  flex: 2; /* 左右部分平分宽度 */
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.el-form-item {
  margin-bottom: 25px;
}

.el-form-item__label {
  color: #333;
  font-weight: 500;
}

.el-button--danger {
  background-color: #f44336;
  border-color: #f44336;
}

.el-button--danger:hover {
  background-color: #d32f2f;
  border-color: #d32f2f;
}



.goods-table {
  width: 100%;
  margin-bottom: 25px;
  border-collapse: collapse;
  border-radius: 10px;
}

.goods-table th,
.goods-table td {
  border: 1px solid #2f78cb;
  padding: 15px;
  text-align: left;
  
}

.goods-table th {
  background-color: #e6f0ff;
  font-weight: bold;
}

.file-upload {
  display: flex;
  align-items: center;
}

.file-upload input[type="file"] {
  margin-right: 15px;
}

.payment-image {
  max-width: 100%;
  border-radius: 4px;
  margin-top: 15px;
}

.button-group {
  display: flex;
  align-items: center;
}

.button-group.el-button {
  margin-right: 15px;
}
</style>